package com.zcy.example;

import com.zcy.example.pojo.Item;
import com.zcy.example.pojo.SearchResult;
import com.zcy.example.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SolrPingResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: zcy
 * @data: 17:50 2017/11/2
 */
@RestController
public class SolrController {

    @Resource(name = "client")
    private SolrClient client;

    @Autowired
    private SearchService searchService;


    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String testSolr() throws IOException, SolrServerException {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery("*:*");
        solrQuery.setStart(1);
        solrQuery.setRows(10);
        QueryResponse query = client.query(solrQuery);
        SolrDocumentList results = query.getResults();

        return results.toString();
    }

    @RequestMapping(value = "/get",method = RequestMethod.GET)
    public String testBean() throws IOException, SolrServerException {

        Item item = new Item();
        item.setId("3");
        item.setName("冰箱4444");
        item.setDescription("三门冰箱,新鲜,速冻");
        item.setCategory("家电");
        item.setKeywords("三门,冰箱");
        item.setPrice(3999L);
        item.setTitle("测试");

        SolrPingResponse ping = client.ping();
        System.out.println("ping.toString() = " + ping.toString());
        client.addBean(item);
        client.commit();
        return "success";

    }

    @RequestMapping(value="/query", method=RequestMethod.GET)
    public SearchResult search(@RequestParam("q")String queryString,
                               @RequestParam(defaultValue="1")Integer page,
                               @RequestParam(defaultValue="60")Integer rows) {
        //查询条件不能为空
        if (StringUtils.isBlank(queryString)) {
//            return TaotaoResult.build(400, "查询条件不能为空");
            return null;
        }

        SearchResult searchResult = null;
        try {
            searchResult = searchService.search(queryString, page, rows);
        } catch (Exception e) {
            e.printStackTrace();
//            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
            return null;
        }
        return searchResult;

    }

}
